import FormLayout from "@/components/forms/formLayout"
import styled from "@emotion/styled"
import EasyFormProvider from "@/components/forms/EasyFormProvider"
import _ from "lodash"
import { useNavigate } from "react-router-dom"
import { toast } from "react-toastify"
import ApiFetchers from "@/apis/api_fetchers"
import { useAtom } from "jotai"
import { SetInitVerifyAtom, SetVerifyAtom, verifyAtom } from "@/pages/AccountPage/atoms/verify"

interface SetPassword {
    password: string
}
const sleep = (delay: number | undefined) => new Promise((resolve) => setTimeout(resolve, delay))

const VerifyPassword = () => {
    const navigate = useNavigate()
    const [verifyData] = useAtom(verifyAtom)
    const [, setVerifyData] = useAtom(SetVerifyAtom)
    const [, setInitVerifyData] = useAtom(SetInitVerifyAtom)
    // const isSetPassword = verifyData?.type === "create"
    // const text = isSetPassword ? "Create Login password" : "Set New Password"
    const isSetForgetPassword =
        verifyData &&
        (verifyData?.field === "email" || verifyData?.field === "phone") &&
        verifyData?.type === "forget"

    console.log("setVerify", verifyData, isSetForgetPassword)

    const handleConfirm = _.throttle(async (data: SetPassword) => {
        if (isSetForgetPassword) {
            await sleep(500)
            // 这里当前是通过手机设置忘记密码,此参数只能是不通过手机验证码方式的接口才会用到。
            // const params = {
            //     password: "",
            //     newPassword: data.password,
            // }

            //通过手机验证码修改密码接口需要的参数
            const resetParams = {
                code: verifyData?.code,
                new_password: data.password,
                otp_id: verifyData?.otpId,
            }
            const res = await ApiFetchers.resetPasswordWithOtpCode(resetParams)
            if (res) {
                toast("success to reset password")
                setInitVerifyData()
                navigate("/")
            } else {
                toast("faied to reset password")
            }
        } else {
            // 这里验证旧密码
            const res = await ApiFetchers.refAuthPassword(data)
            if (res) {
                setVerifyData({
                    ...verifyData,
                    type: "edit",
                    field: "password",
                    oldPassword: data.password,
                })
                navigate("/s-account/form/password")
            } else {
                toast("Invalid old password")
            }
        }
    }, 5000)
    const onBack = () => {
        console.log("返回！！！")
        if (isSetForgetPassword) {
            setInitVerifyData()
            navigate("/forgetPassword/")
        } else {
            setInitVerifyData()
            navigate("/s-account")
        }
    }
    return (
        <FormLayout
            title={isSetForgetPassword ? "Set New Password" : "Enter old password"}
            description={isSetForgetPassword ? "" : "Please enter your old password to verify"}
            backPath="/s-account"
            onBack={onBack}
        >
            <EasyFormProvider
                // @ts-ignore
                onSubmit={handleConfirm}
                queryList={
                    isSetForgetPassword
                        ? ["password", "submitButton"]
                        : ["passwordNoVerifyBox", "submitButton"]
                }
                buttonText="Confirm"
            />
        </FormLayout>
    )
}

export default VerifyPassword
